
import net from 'net';
import EventEmitter from 'events';
import Socket from './Socket';

export default class Server {
    private port:number;
    private socketMap:Map<string, Socket> = new Map();
    private eventEmitter:EventEmitter;
    constructor(params : {port:number}) {
        this.port = params.port
        this.eventEmitter = new EventEmitter()
    }

    on<T>(event:'start'|'data'|'destroy', listener:(data:T) => void) {
        this.eventEmitter.on(event, listener)
        return this
    }

    start() {
        const server = net.createServer({allowHalfOpen : false}, socket => {
            const sock = new Socket(socket)
            sock.on<DataType>('data', data => {
                if(data.cmd === '0001') { //注册
                    sock.deviceId = data.deviceId
                    this.socketMap.set(data.deviceId, sock)
                }else { //非注册
                    if(!this.socketMap.has(data.deviceId) || data.deviceId != sock.deviceId) {
                        console.log('it is serve')
						console.log(this.socketMap.has(data.deviceId))
                        console.log(data.deviceId, sock.deviceId)
                        sock.destroy()
                        return
                    }
                }

                this.eventEmitter.emit('data', data)
            })

            sock.on('destroy', () => {
                this.socketMap.delete(sock.deviceId)
                this.eventEmitter.emit('destroy', sock.deviceId)
            })

        })

        server.on('error', (error) => {
            console.log('server error')
            console.log(error)
        })

        server.listen({ port: this.port }, () => {
            this.eventEmitter.emit('start')
        });
    }

    

    send(deviceId:string, data:string) {
        let sock = this.socketMap.get(deviceId)
        if(!sock) return false
        sock.send(data)
    }

    getSock(deviceId:string) {
        console.log(this.socketMap.size)
        return this.socketMap.get(deviceId)
    }

    
}